package cn.tedu.controller;

import cn.tedu.domain.User;
import cn.tedu.exception.MsgException;
import cn.tedu.service.UserService;
import cn.tedu.utils.MD5Utils;
import cn.tedu.utils.VerifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 获取验证码
     *
     * @param resp
     * @param session
     */
    @RequestMapping(value = "/valiImg.action")
    public void getValiImg(HttpServletResponse resp, HttpSession session) {
        //1.控制浏览器不使用缓存
        resp.setDateHeader("Expires", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("pragma", "no-cache");
        try {
            //2.生成验证码图片。
            VerifyCode vc = new VerifyCode();
            vc.drawImage(resp.getOutputStream());
            //3.获取验证码图片字符
            String code = vc.getCode();
            //4.将生成的验证码加入session域中
            session.setAttribute("valistr", code);
            System.out.println("Verify Code: " + code);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param remname
     * @param autologin
     * @param model
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login.action")
    public String login(String username, String password, String remname, String autologin, Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        //1.乱码解决
        //2.获取请求参数
        //3.记住用户名处理
        if ("true".equals(remname)) {
            try {
                Cookie remnamec = new Cookie("remname", URLEncoder.encode(username, "utf-8"));
                remnamec.setPath(request.getContextPath() + "/");
                remnamec.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(remnamec);
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
        }
        //4.30天内自动登录处理
        if ("true".equals(autologin)) {
            try {
                Cookie autologinc = new Cookie("autologin", URLEncoder.encode(username, "utf-8") + "#" + MD5Utils.md5(password));
                autologinc.setPath(request.getContextPath() + "/");
                autologinc.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(autologinc);
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
        }
        //5.调用Service进行登录
        User user = userService.loginUser(username, MD5Utils.md5(password));
        if (user != null) {
            //6.登录成功回到主页
            session.setAttribute("user", user);
            return "redirect:/index.jsp";
        } else {
            //6.登录失败回登录页面提示
            model.addAttribute("msg", "用户名密码不正确！");
            return "forward:/WEB-INF/jsp/login.jsp";
        }
    }

    /**
     * 注册用户
     *
     * @param user
     * @param errors
     * @param valistr
     * @param model
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/regist.action")
    public String regist(@Valid User user, Errors errors, String valistr, Model model, HttpServletRequest req, HttpServletResponse resp) {

        // 校验验证码
        String valistr1 = (String) req.getSession().getAttribute("valistr");
        if (valistr == null || valistr1 == null || !valistr.equals(valistr1)) {
            model.addAttribute("msg", "验证码错误!");
            // TODO: PrintWriter会导致: 重新回到的注册页面，中文无法正常显示
            return "forward:/WEB-INF/jsp/regist.jsp";
        }

        // 校验数据
        if (errors.hasErrors()) { // 校验数据出错
            List<FieldError> errList = errors.getFieldErrors();
            for (FieldError err : errList
            ) {
                String field = err.getField();
                String msg = err.getDefaultMessage();
                System.out.println("error-> " + field + ": " + msg);
            }

            model.addAttribute("msg", "后台校验数据出错");
            // TODO: PrintWriter会导致: 重新回到的注册页面，中文无法正常显示
            return "forward:/WEB-INF/jsp/regist.jsp";
        }

        // 调用Service注册用户
        try {
            user.setPassword(MD5Utils.md5(user.getPassword()));
            userService.registUser(user);
        } catch (MsgException e) {
            model.addAttribute("msg", e.getMessage());
            return "forward:/WEB-INF/jsp/regist.jsp";
        }

        // 回到主页
        // writer.write("<h1 align='center'><font color='red'>恭喜，注册成功，3秒之后跳转到首页..</font></h1>");
        resp.setHeader("refresh", "3;url=" + req.getContextPath());
        return "forward:/WEB-INF/jsp/success.jsp";
    }

    /**
     * 用户登出
     *
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logout.action")
    public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        //--注销
        session.invalidate();
        //--删除30天内自动登录cookie
        Cookie autologinc = new Cookie("autologin", "");
        autologinc.setPath(request.getContextPath() + "/");
        autologinc.setMaxAge(0);
        response.addCookie(autologinc);
        //--重定向回主页
        return "redirect:/index.jsp";
    }

    /**
     * Ajax校验用户名
     *
     * @param username
     * @return
     */
    @RequestMapping(value = "/ajaxCheckUserName.action", produces = "application/json;charset=utf-8")
    public @ResponseBody
    String ajaxCheckUserName(String username) {
        System.out.println("ajaxCheckUserName");
        //调用Service查询用户名是否可用
        if (userService.userNameIsOK(username)) {
            return "用户名可用";
        } else {
            return "用户名不可用";
        }
    }

    /**
     * https://www.cnblogs.com/striver-zhu/p/7158623.html
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/testChinese.action", produces = {"text/javascript;charset=UTF-8"})
    public String testChinese(HttpServletRequest req, HttpServletResponse resp) {
        // 回到主页
        resp.setHeader("refresh", "3;url=" + req.getContextPath());
        return "forward:/WEB-INF/jsp/success.jsp";
    }

    @RequestMapping(value = "/getUTF8String", produces = {"text/javascript;charset=UTF-8"})
    public @ResponseBody
    String getUTF8String() {
        return "我不是乱码！";
    }

}
